﻿using System;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Web;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;

/// <summary>
/// Summary description for HTMLShot
/// </summary>
public static class HTMLShot
{
    private struct ScreenShotParameters
    {
        public string HTMLString;
        public Uri FullUrl;
        public Stream StreamHolder;
        public System.Drawing.Imaging.ImageFormat BitmapFormat;
        public int? Width;
        public int? Height;
    }
    private class ScreenShot
    {
        private string TempFilePath;
        private ScreenShotParameters Parameters;
        public Bitmap HTMLImage;

        public ScreenShot() { }
        public ScreenShot(ScreenShotParameters scp)
        {
            TempFilePath = Path.GetTempFileName().Replace("tmp", "html");
            Parameters = scp;
            StartSTAThread();
        }

        private void StartSTAThread()
        {
            try
            {
                ThreadStart ts = new ThreadStart(GenerateScreenshot);
                Thread t = new Thread(ts);
                t.SetApartmentState(ApartmentState.STA);
                t.Start();

                // TODO find the proper way to wait for a thread
                // wait for the thread
                while (t.IsAlive)
                {
                    Thread.Sleep(25);
                }
            }
            catch (Exception ex) { }
        }
        private void GenerateScreenshot()
        {
            try
            {
                string path;
                if ((Parameters.HTMLString != "")&&(Parameters.HTMLString != null))
                {
                    BuildHTMLFile();
                    path = TempFilePath;
                }
                else
                {
                    path = Parameters.FullUrl.AbsoluteUri;
                }
                // Load the webpage into a WebBrowser control
                WebBrowser wb = new WebBrowser();
                wb.ScrollBarsEnabled = false;
                wb.ScriptErrorsSuppressed = true;
                wb.Navigate(path);
                while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }
                try
                {
                    File.Delete(path);
                }
                catch (Exception ex) { }
                // Set the size of the WebBrowser control
                wb.Width = (Parameters.Width != null && Parameters.Width != 0) ? (int)Parameters.Width : wb.Document.Body.ScrollRectangle.Width + 20;
                wb.Height = (Parameters.Height != null && Parameters.Height != 0) ? (int)Parameters.Height : wb.Document.Body.ScrollRectangle.Height + 50;

                // Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control
                HTMLImage = new Bitmap(wb.Width, wb.Height);
                wb.DrawToBitmap(HTMLImage, new Rectangle(0, 0, wb.Width, wb.Height));
                wb.Dispose();

                MemoryStream ms = new MemoryStream();
                Bitmap tempBitmap = new Bitmap(HTMLImage);
                tempBitmap.Save(ms, Parameters.BitmapFormat);
                ms.WriteTo(Parameters.StreamHolder);
                HTMLImage.Dispose();
                tempBitmap.Dispose();
            }
            catch (Exception ex) { }
        }
        private void BuildHTMLFile()
        {
            TextWriter tw = new StreamWriter(TempFilePath);
            FormatHTMLString();
            tw.Write(Parameters.HTMLString);
            tw.Close();
        }
        private void FormatHTMLString()
        {
            try
            {
                /*
                    Replaces in the html code some characters, leaving the string in only one line,
                    with the < replaced to a left pointing arrow (\u2190) and > replaced to the right
                    pointing arrow (\u2192). This values are needed to then convert the string into
                    html - readeble code.

                    2190 -> 003C
                    2192 -> 003E
                */
                Parameters.HTMLString = Parameters.HTMLString.Replace("\u2190", "\u003C");
                Parameters.HTMLString = Parameters.HTMLString.Replace("\u2192", "\u003E");

                /*
                 * The includes for the WebBrowser class, don't support dynamic paths,
                 * so here is neccesary to replace all realtive path to complete uri strings.
                 */

                //Replace "../" relative path to aboslute uri path("http://localhost/virutladirectory/etc").
                int relativesPathCount = GetRelativePathDepth("../", 1);
                string[] splitPattern = new string[1] { "/" };
                string[] splitedFullPath = Parameters.FullUrl.AbsoluteUri.Split(splitPattern, StringSplitOptions.None);

                for (int patternDepth = 1; patternDepth <= relativesPathCount; patternDepth++)
                {
                    string replacementPattern = "(\\.\\.[/]{1,}){1," + patternDepth.ToString() + "}(([a-zA-Z0-9-_]{1,}[/]{1,}){1,}[a-zA-Z0-9-_]{1,}\\.[a-zA-Z0-9-_]{1,})";
                    string matchPatterns = "['|\"]" + replacementPattern;
                    if (Regex.Matches(Parameters.HTMLString, matchPatterns, RegexOptions.IgnoreCase).Count > 0)
                    {
                        string applicationPath = BuildApplicationPath(splitedFullPath, patternDepth + 1);
                        Parameters.HTMLString = Regex.Replace(Parameters.HTMLString, replacementPattern, applicationPath + "$2", RegexOptions.Multiline);
                    }
                }
                
                //Complete url type "/virtual directory name/directory1" to "http:///virtual directory name/directory1"
                Parameters.HTMLString = Regex.Replace(Parameters.HTMLString, "(['|\"])(([/]{1,}([a-zA-Z0-9-_]{1,})){1,}[a-zA-Z0-9-_]{1,}\\.[a-zA-Z0-9-_]{1,})", "$1" + splitedFullPath[0] + "//" + splitedFullPath[2] + "$2", RegexOptions.Multiline);

                //Replace absolute path to "http:///virtual directory name/directory1/etc" format.
                Parameters.HTMLString = Regex.Replace(Parameters.HTMLString, "(['|\"])(file:///)([^:]{1,}:[/]{1,})(([\\w\\d_-]{1,}([/]{1,})){1,})(" + splitedFullPath[3] + "[/]{1,})((([\\w\\d_-]{1,}([/]{1,})){1,})([\\w\\d_-]{1,}\\.[\\w\\d_-]{1,}))", "$1" + splitedFullPath[0] + "//" + splitedFullPath[2] + "/$7$8", RegexOptions.Multiline);

                //Complete others paths
                string directoryNamePattern = "[^\\^\\*\"/\\\\\\[\\]:;\\|=]{1,}";
                try
                {
                    Parameters.HTMLString = Regex.Replace(Parameters.HTMLString, "(['|\"])(((" + directoryNamePattern + ")\\." + directoryNamePattern + ")|(((?!-//W3C//DTD XHTML 1.0)(" + directoryNamePattern + "[/]{1,})){1,}" + directoryNamePattern + "\\." + directoryNamePattern + "))", "$1" + Parameters.FullUrl.AbsoluteUri.Replace(splitedFullPath[splitedFullPath.Length - 1], "") + "$2", RegexOptions.Multiline);
                }
                catch (ArgumentException argex)
                {
                    Parameters.HTMLString = Regex.Replace(Parameters.HTMLString, "(['|\"])(((" + directoryNamePattern + ")\\." + directoryNamePattern + ")|(((?!-//W3C//DTD XHTML 1.0)(" + directoryNamePattern + "[/]{1,})){1,}" + directoryNamePattern + "\\." + directoryNamePattern + "))", "$1" + Parameters.FullUrl.AbsoluteUri + "$2", RegexOptions.Multiline);
                }
            }
            catch (Exception ex)
            {

            }
        }
        private int GetRelativePathDepth(string pattern,int count)
        {
            try
            {
                if (Parameters.HTMLString.Contains(pattern))
                {
                    count++;
                    pattern += "../";
                    count = GetRelativePathDepth(pattern,count);
                }
                return count;
            }
            catch (Exception ex)
            {
                return 1;
            }
        }
        private string BuildApplicationPath(string[] splitedUrlReferer, int depth)
        {
            string applicationPath = "";
            try
            {
                for (int iDirectory = 0; iDirectory < splitedUrlReferer.Length - depth; iDirectory++)
                {
                    applicationPath += splitedUrlReferer[iDirectory] + "/";
                }
            }
            catch (Exception ex)
            {

            }
            return applicationPath;
        }
    }

    /// <summary>
    /// Get a bitmap of all the HTML content of the Request file.
    /// </summary>
    /// <param name="fullUrl">The url of the screen to get the shot.</param>
    /// <returns>A bitmap with the HTML content.</returns>
    public static Bitmap GetHTMLShot(string fullUrl)
    {
        try
        {
            ScreenShotParameters scp = new ScreenShotParameters();
            scp.FullUrl = ValidateURL(fullUrl);
            ScreenShot sc = new ScreenShot(scp);
            return sc.HTMLImage;
        }
        catch (Exception ex) { return null; }
    }
    /// <summary>
    /// Get a bitmap of all the HTML content of the Request file.
    /// </summary>
    /// <param name="fullUrl">The url of the screen to get the shot.</param>
    /// <param name="imageWidth">The HTMLShot width. If it's cero or null, take the total width of the HTML content.</param>
    /// <param name="imageHeight">The HTMLShot height. If it's cero or null, take the total height of the HTML content.</param>
    /// <returns>A bitmap with the HTML content.</returns>
    public static Bitmap GetHTMLShot(string fullUrl, int? imageWidth, int? imageHeight)
    {
        try
        {
            ScreenShotParameters scp = new ScreenShotParameters();
            scp.FullUrl = ValidateURL(fullUrl);
            scp.HTMLString = ""; scp.Width = imageWidth; scp.Height = imageHeight;
            ScreenShot sc = new ScreenShot(scp);
            return sc.HTMLImage;
        }
        catch (Exception ex) { return null; }
    }
    /// <summary>
    /// Get a bitmap of all the HTML content of the Request file.
    /// </summary>
    /// <param name="fullUrl">The url of the screen to get the shot.</param>
    /// <param name="streamHolder">A stream where the bitmap generated is going to keep.</param>
    public static void GetHTMLShot(string fullUrl, Stream streamHolder)
    {
        try
        {
            ScreenShotParameters scp = new ScreenShotParameters();
            scp.FullUrl = ValidateURL(fullUrl); scp.StreamHolder = streamHolder; scp.BitmapFormat = System.Drawing.Imaging.ImageFormat.Bmp; scp.HTMLString = "";
            ScreenShot sc = new ScreenShot(scp);
        }
        catch (Exception ex) { }
    }
    /// <summary>
    /// Save a bitmap of all the HTML content of the Request file into a stream.
    /// </summary>
    /// <param name="fullUrl">The url of the screen to get the shot.</param>
    /// <param name="streamHolder">A stream where the bitmap generated is going to keep.</param>
    /// <param name="imageFormat">The format of the bitmap generated.</param>
    public static void GetHTMLShot(string fullUrl, Stream streamHolder, System.Drawing.Imaging.ImageFormat imageFormat)
    {
        try
        {
            ScreenShotParameters scp = new ScreenShotParameters();
            scp.FullUrl = ValidateURL(fullUrl); scp.StreamHolder = streamHolder; scp.BitmapFormat = imageFormat; scp.HTMLString = "";
            ScreenShot sc = new ScreenShot(scp);
        }
        catch (Exception ex) { }
    }
    /// <summary>
    /// Save a bitmap of all the HTML content of the Request file into a stream.
    /// </summary>
    /// <param name="fullUrl">The url of the screen to get the shot.</param>
    /// <param name="streamHolder">A stream where the bitmap generated is going to keep.</param>
    /// <param name="imageWidth">The HTMLShot width. If it's cero or null, take the total width of the HTML content.</param>
    /// <param name="imageHeight">The HTMLShot height. If it's cero or null, take the total height of the HTML content.</param>
    public static void GetHTMLShot(string fullUrl, Stream streamHolder, int? imageWidth, int? imageHeight)
    {
        try
        {
            ScreenShotParameters scp = new ScreenShotParameters();
            scp.FullUrl = ValidateURL(fullUrl); scp.StreamHolder = streamHolder; scp.BitmapFormat = System.Drawing.Imaging.ImageFormat.Bmp;
            scp.Width = imageWidth; scp.Height = imageHeight; scp.HTMLString = "";
            ScreenShot sc = new ScreenShot(scp);
        }
        catch (Exception ex) { }
    }
    /// <summary>
    /// Save a bitmap of all the HTML content of the Request file into a stream.
    /// </summary>
    /// <param name="fullUrl">The url of the screen to get the shot.</param>
    /// <param name="streamHolder">A stream where the bitmap generated is going to keep.</param>
    /// <param name="imageFormat">The format of the bitmap generated.</param>
    /// <param name="imageWidth">The HTMLShot width. If it's cero or null, take the total width of the HTML content.</param>
    /// <param name="imageHeight">The HTMLShot height. If it's cero or null, take the total height of the HTML content.</param>
    public static void GetHTMLShot(string fullUrl, Stream streamHolder, System.Drawing.Imaging.ImageFormat imageFormat, int? imageWidth, int? imageHeight)
    {
        try
        {
            ScreenShotParameters scp = new ScreenShotParameters();
            scp.FullUrl = ValidateURL(fullUrl); scp.StreamHolder = streamHolder; scp.BitmapFormat = imageFormat;
            scp.Width = imageWidth; scp.Height = imageHeight; scp.HTMLString = "";
            ScreenShot sc = new ScreenShot(scp);
        }
        catch (Exception ex) { }
    }

    /// <summary>
    /// Save a bitmap of all the HTML content of the Request file into a stream.
    /// </summary>
    /// <param name="fullUrl">The url of the screen to get the shot.</param>
    /// <param name="htmlString">HTML content formated to string what will be draw it to a bitmap.</param>
    /// <returns></returns>
    public static Bitmap GetHTMLShot(string fullUrl, string htmlString)
    {
        try
        {
            ScreenShotParameters scp = new ScreenShotParameters();
            scp.FullUrl = ValidateURL(fullUrl); scp.HTMLString = htmlString;
            ScreenShot sc = new ScreenShot(scp);
            return sc.HTMLImage;
        }
        catch (Exception ex) { return null; }
    }
    /// <summary>
    /// Get a bitmap what contains the HTML content.
    /// </summary>
    /// <param name="fullUrl">The url of the screen to get the shot, used to complete all url of the HTMLString.</param>
    /// <param name="htmlString">HTML content formated to string what will be draw it to a bitmap.</param>
    /// <param name="imageWidth">The HTMLShot width. If it's cero or null, take the total width of the HTML content.</param>
    /// <param name="imageHeight">The HTMLShot height. If it's cero or null, take the total height of the HTML content.</param>
    /// <returns></returns>
    public static Bitmap GetHTMLShot(string fullUrl, string htmlString, int? imageWidth, int? imageHeight)
    {
        try
        {
            ScreenShotParameters scp = new ScreenShotParameters();
            scp.FullUrl = ValidateURL(fullUrl); scp.HTMLString = htmlString; scp.Width = imageWidth; scp.Height = imageHeight;
            ScreenShot sc = new ScreenShot(scp);
            return sc.HTMLImage;
        }
        catch (Exception ex) { return null; }
    }
    /// <summary>
    /// Get a bitmap what contains the HTML content.
    /// </summary>
    /// <param name="fullUrl">The url of the screen to get the shot, used to complete all url of the HTMLString.</param>
    /// <param name="htmlString">HTML content formated to string what will be draw it to a bitmap.</param>
    /// <param name="streamHolder">A stream where the bitmap generated is going to keep.</param>
    public static void GetHTMLShot(string fullUrl, string htmlString, Stream streamHolder)
    {
        try
        {
            ScreenShotParameters scp = new ScreenShotParameters();
            scp.FullUrl = ValidateURL(fullUrl); scp.HTMLString = htmlString; scp.StreamHolder = streamHolder; scp.BitmapFormat = System.Drawing.Imaging.ImageFormat.Bmp;
            ScreenShot sc = new ScreenShot(scp);
        }
        catch (Exception ex) { }
    }
    /// <summary>
    ///  Save a bitmap what contains the HTML content into a stream
    /// </summary>
    /// <param name="fullUrl">The url of the screen to get the shot, used to complete all url of the HTMLString.</param>
    /// <param name="htmlString">HTML content formated to string what will be draw it to a bitmap.</param>
    /// <param name="streamHolder">A stream where the bitmap generated is going to keep.</param>
    /// <param name="imageWidth">The HTMLShot width. If it's cero or null, take the total width of the HTML content.</param>
    /// <param name="imageHeight">The HTMLShot height. If it's cero or null, take the total height of the HTML content.</param>
    public static void GetHTMLShot(string fullUrl, string htmlString, Stream streamHolder, int? imageWidth, int? imageHeight)
    {
        try
        {
            ScreenShotParameters scp = new ScreenShotParameters();
            scp.FullUrl = ValidateURL(fullUrl); scp.HTMLString = htmlString; scp.StreamHolder = streamHolder; scp.BitmapFormat = System.Drawing.Imaging.ImageFormat.Bmp;
            scp.Width = imageWidth; scp.Height = imageHeight;
            ScreenShot sc = new ScreenShot(scp);
        }
        catch (Exception ex) { }
    }
    /// <summary>
    ///  Save a bitmap what contains the HTML content into a stream
    /// </summary>
    /// <param name="fullUrl">The url of the screen to get the shot, used to complete all url of the HTMLString.</param>
    /// <param name="htmlString">HTML content formated to string what will be draw it to a bitmap.</param>
    /// <param name="streamHolder">A stream where the bitmap generated is going to keep.</param>
    /// <param name="imageFormat">The format of the bitmap generated.</param>
    public static void GetHTMLShot(string fullUrl, string htmlString, Stream streamHolder, System.Drawing.Imaging.ImageFormat imageFormat)
    {
        try
        {
            ScreenShotParameters scp = new ScreenShotParameters();
            scp.FullUrl = ValidateURL(fullUrl); scp.HTMLString = htmlString; scp.StreamHolder = streamHolder; scp.BitmapFormat = imageFormat;
            ScreenShot sc = new ScreenShot(scp);
        }
        catch (Exception ex) { }
    }
    /// <summary>
    ///  Save a bitmap what contains the HTML content into a stream
    /// </summary>
    /// <param name="fullUrl">The url of the screen to get the shot, used to complete all url of the HTMLString.</param>
    /// <param name="htmlString">HTML content formated to string what will be draw it to a bitmap.</param>
    /// <param name="streamHolder">A stream where the bitmap generated is going to keep.</param>
    /// <param name="imageFormat">The format of the bitmap generated.</param>
    /// <param name="imageWidth">The HTMLShot width. If it's cero or null, take the total width of the HTML content.</param>
    /// <param name="imageHeight">The HTMLShot height. If it's cero or null, take the total height of the HTML content.</param>
    public static void GetHTMLShot(string fullUrl, string htmlString, Stream streamHolder, System.Drawing.Imaging.ImageFormat imageFormat, int? imageWidth, int? imageHeight)
    {
        try
        {
            ScreenShotParameters scp = new ScreenShotParameters();
            scp.FullUrl = ValidateURL(fullUrl); scp.HTMLString = htmlString; scp.StreamHolder = streamHolder; scp.BitmapFormat = imageFormat;
            scp.Width = imageWidth; scp.Height = imageHeight;
            ScreenShot sc = new ScreenShot(scp);
        }
        catch (Exception ex) { }
    }

    /// <summary>
    ///  Save a bitmap what contains the HTML content into a stream
    /// </summary>
    /// <param name="fullUrl">The url of the screen to get the shot, used to complete all url of the HTMLString.</param>
    /// <param name="htmlStringByteEncoded">Encoded HTML content formated to string what will be draw it to a bitmap.</param>
    /// <returns></returns>
    public static Bitmap GetHTMLShot(string fullUrl, byte[] htmlStringByteEncoded)
    {
        try
        {
            ScreenShotParameters scp = new ScreenShotParameters();
            scp.HTMLString = DeserializeHTMLStringEncoded(htmlStringByteEncoded);
            scp.FullUrl = ValidateURL(fullUrl);
            ScreenShot sc = new ScreenShot(scp);
            return sc.HTMLImage;
        }
        catch (Exception ex) { return null; }
    }
    /// <summary>
    /// Get a bitmap what contains the HTML content.
    /// </summary>
    /// <param name="fullUrl">The url of the screen to get the shot, used to complete all url of the HTMLString.</param>
    /// <param name="htmlStringByteEncoded">Encoded HTML content formated to string what will be draw it to a bitmap.</param>
    /// <param name="imageWidth">The HTMLShot width. If it's cero or null, take the total width of the HTML content.</param>
    /// <param name="imageHeight">The HTMLShot height. If it's cero or null, take the total height of the HTML content.</param>
    /// <returns></returns>
    public static Bitmap GetHTMLShot(string fullUrl, byte[] htmlStringByteEncoded, int? imageWidth, int? imageHeight)
    {
        try
        {
            ScreenShotParameters scp = new ScreenShotParameters();
            scp.HTMLString = DeserializeHTMLStringEncoded(htmlStringByteEncoded);
            scp.FullUrl = ValidateURL(fullUrl); scp.Width = imageWidth; scp.Height = imageHeight;
            ScreenShot sc = new ScreenShot(scp);
            return sc.HTMLImage;
        }
        catch (Exception ex) { return null; }
    }
    /// <summary>
    /// Get a bitmap what contains the HTML content.
    /// </summary>
    /// <param name="fullUrl">The url of the screen to get the shot, used to complete all url of the HTMLString.</param>
    /// <param name="htmlStringByteEncoded">Encoded HTML content formated to string what will be draw it to a bitmap.</param>
    /// <param name="streamHolder">A stream where the bitmap generated is going to keep.</param>
    public static void GetHTMLShot(string fullUrl, byte[] htmlStringByteEncoded, Stream streamHolder)
    {
        try
        {
            ScreenShotParameters scp = new ScreenShotParameters();
            scp.HTMLString = DeserializeHTMLStringEncoded(htmlStringByteEncoded);
            scp.FullUrl = ValidateURL(fullUrl); scp.StreamHolder = streamHolder; scp.BitmapFormat = System.Drawing.Imaging.ImageFormat.Bmp;
            ScreenShot sc = new ScreenShot(scp);
        }
        catch (Exception ex) { }
    }
    /// <summary>
    ///  Save a bitmap what contains the HTML content into a stream
    /// </summary>
    /// <param name="fullUrl">The url of the screen to get the shot, used to complete all url of the HTMLString.</param>
    /// <param name="htmlStringByteEncoded">Encoded HTML content formated to string what will be draw it to a bitmap.</param>
    /// <param name="streamHolder">A stream where the bitmap generated is going to keep.</param>
    /// <param name="imageWidth">The HTMLShot width. If it's cero or null, take the total width of the HTML content.</param>
    /// <param name="imageHeight">The HTMLShot height. If it's cero or null, take the total height of the HTML content.</param>
    public static void GetHTMLShot(string fullUrl, byte[] htmlStringByteEncoded, Stream streamHolder, int? imageWidth, int? imageHeight)
    {
        try
        {
            ScreenShotParameters scp = new ScreenShotParameters();
            scp.HTMLString = DeserializeHTMLStringEncoded(htmlStringByteEncoded);
            scp.FullUrl = ValidateURL(fullUrl); scp.StreamHolder = streamHolder; scp.BitmapFormat = System.Drawing.Imaging.ImageFormat.Bmp;
            scp.Width = imageWidth; scp.Height = imageHeight;
            ScreenShot sc = new ScreenShot(scp);
        }
        catch (Exception ex) { }
    }
    /// <summary>
    ///  Save a bitmap what contains the HTML content into a stream
    /// </summary>
    /// <param name="fullUrl">The url of the screen to get the shot, used to complete all url of the HTMLString.</param>
    /// <param name="htmlStringByteEncoded">Encoded HTML content formated to string what will be draw it to a bitmap.</param>
    /// <param name="streamHolder">A stream where the bitmap generated is going to keep.</param>
    /// <param name="imageFormat">The format of the bitmap generated.</param>
    public static void GetHTMLShot(string fullUrl, byte[] htmlStringByteEncoded, Stream streamHolder, System.Drawing.Imaging.ImageFormat imageFormat)
    {
        try
        {
            ScreenShotParameters scp = new ScreenShotParameters();
            scp.HTMLString = DeserializeHTMLStringEncoded(htmlStringByteEncoded);
            scp.FullUrl = ValidateURL(fullUrl); scp.StreamHolder = streamHolder; scp.BitmapFormat = imageFormat;
            ScreenShot sc = new ScreenShot(scp);
        }
        catch (Exception ex) { }
    }
    /// <summary>
    ///  Save a bitmap what contains the HTML content into a stream
    /// </summary>
    /// <param name="fullUrl">The url of the screen to get the shot, used to complete all url of the HTMLString.</param>
    /// <param name="htmlStringByteEncoded">Encoded HTML content formated to string what will be draw it to a bitmap.</param>
    /// <param name="streamHolder">A stream where the bitmap generated is going to keep.</param>
    /// <param name="imageFormat">The format of the bitmap generated.</param>
    /// <param name="imageWidth">The HTMLShot width. If it's cero or null, take the total width of the HTML content.</param>
    /// <param name="imageHeight">The HTMLShot height. If it's cero or null, take the total height of the HTML content.</param>
    public static void GetHTMLShot(string fullUrl, byte[] htmlStringByteEncoded, Stream streamHolder, System.Drawing.Imaging.ImageFormat imageFormat, int? imageWidth, int? imageHeight)
    {
        try
        {
            ScreenShotParameters scp = new ScreenShotParameters();
            scp.HTMLString = DeserializeHTMLStringEncoded(htmlStringByteEncoded);
            scp.FullUrl = ValidateURL(fullUrl); scp.StreamHolder = streamHolder; scp.BitmapFormat = imageFormat;
            scp.Width = imageWidth; scp.Height = imageHeight;
            ScreenShot sc = new ScreenShot(scp);
        }
        catch (Exception ex) { }
    }

    private static Uri ValidateURL(string url)
    {
        try{
            Uri validatedURL = new Uri(url);
            return validatedURL;
        }
        catch (Exception ex) { return null;}
    }
    private static string DeserializeHTMLStringEncoded(byte[] htmlStringByteEncoded)
    {
        try
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            ms.Write(htmlStringByteEncoded, 0, htmlStringByteEncoded.Length);
            ms.Seek(0, 0);
            return (string)bf.Deserialize(ms);
        }
        catch (Exception ex) { return null; }
    }
}